package me.zhengjie.modules.fund.service.impl;

import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.fund.domain.Fund;
import me.zhengjie.modules.fund.repository.FundRepository;
import me.zhengjie.modules.fund.service.FundService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;

@Slf4j
@Service
public class FundServiceImpl implements FundService {
    @Resource
    private FundRepository fundRepository;

    /**
     * @param fund 基金
     * @return
     * @see FundService#create(Fund)
     */
    @Override
    public Fund create(Fund fund) {
        return fundRepository.save(fund);
    }

    /**
     * @param funds 要插入的基金
     * @see FundService#createBatch(List)
     */
    @Override
    public void createBatch(List<Fund> funds) {

        List<Fund> allFunds = findAll();

        List<Fund> insertFunds = new LinkedList<>();
        for (Fund fund : funds) {
            Optional<Fund> optionalFund = allFunds.stream().filter(f -> f.getCode().equals(fund.getCode())).findAny();
            if (!optionalFund.isPresent()) {
                insertFunds.add(fund);
            }
        }
        if (!CollectionUtils.isEmpty(insertFunds)) {
            fundRepository.saveAll(insertFunds);
        }
    }

    @Override
    public List<Fund> findAll() {
        return fundRepository.findAll();
    }

    /**
     * @param code 基金编码
     * @return
     * @see FundService#findByCode(String)
     */
    @Override
    public Fund findByCode(String code) {
        return fundRepository.findByCode(code);
    }
}
